package com.kws.tool.service.impl;


import com.kws.common.security.auth.AuthUtil;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.system.api.domain.SysUser;
import com.kws.tool.dto.ChatDto;
import com.kws.common.config.constant.MinioCommonBucket;
import com.kws.tool.dto.UserMessageDto;
import com.kws.tool.entity.MerchantUserChat;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.tool.mapper.MerchantUserChatMapper;
import com.kws.tool.service.MerchantUserChatService;
import com.kws.tool.vo.UserMessageVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import java.util.ArrayList;
import java.util.List;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商家用户聊天记录(MerchantUserChat)表服务实现类
 *
 * @author yxy
 * @since 2024-10-31 10:45:06
 */
@Service("MerchantUserChatServiceImpl")
public class MerchantUserChatServiceImpl extends ServiceImpl<MerchantUserChatMapper, MerchantUserChat> implements MerchantUserChatService {

    @Resource
    private MerchantUserChatMapper merchantUserChatMapper;

    @Value("${minio.ENDPOINT}")
    private String minioUrl;



    /**
     * 分页查询列表
     */
    @Override
    public Page<MerchantUserChat> pageList(MerchantUserChat merchantUserChat) {
        Page<MerchantUserChat> page = new Page<>(0, 10);
        LambdaQueryWrapper<MerchantUserChat> queryWrapper = Wrappers.lambdaQuery();

        return this.page(page, queryWrapper);
    }

    /**
     * 获取当前用户所有未读信息
     *
     * @return
     */
    @Override
    public List<ChatDto> unreadMessage(Integer type) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        List<MerchantUserChat> list = merchantUserChatMapper.unreadMessage(sysUser.getUserId(),type);
        ArrayList<ChatDto> chatDtos = new ArrayList<>();
        list.forEach(x -> {
            ChatDto chatDto = new ChatDto();
            Long sendUser = x.getSendUser();
            //查询用户发送方数据
            List<MerchantUserChat> chatList = merchantUserChatMapper.listBySendUser(sendUser, sysUser.getUserId(),type);

            chatDto.setSendUser(sendUser);
            chatDto.setCount(chatList.size());
            chatDto.setSendUserName(x.getSendUserName());
            chatDto.setChatList(chatList);
            chatDtos.add(chatDto);
        });
        return chatDtos;
    }

    /**
     * 根据发送者id修改当前用户未读信息为已读
     *
     * @param sendUser
     * @return
     */
    @Override
    public boolean readMessage(Long sendUser) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        boolean flag = merchantUserChatMapper.readMessage(sendUser, sysUser.getUserId());
        return flag;
    }

    @Override
    public Page<UserMessageVo> userMessage(UserMessageDto userMessageDto) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        userMessageDto.setPageSize((userMessageDto.getPageSize() - 1) * userMessageDto.getTotalPage());

        String minioStr = minioUrl + "/" + MinioCommonBucket.HUATAI_PUB_BUCKET + "/";

        if (userMessageDto.getMessageType().equals(3)) {
            //客服消息
            LambdaQueryWrapper<MerchantUserChat> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(MerchantUserChat::getToUser, userId);
            wrapper.eq(MerchantUserChat::getMessageType, userMessageDto.getMessageType());
            wrapper.eq(MerchantUserChat::getStatus, 1);
            wrapper.eq(MerchantUserChat::getEnable, "1");
            List<MerchantUserChat> list = this.list(wrapper);
            Map<Long, List<MerchantUserChat>> merchantUserChatMap = list.stream().collect(Collectors.groupingBy(MerchantUserChat::getSendUser));
            Long count = baseMapper.getServeMessageCount(userId, userMessageDto.getMessageType());
            Page<UserMessageVo> servePage = new Page<>(userMessageDto.getPageSize(), userMessageDto.getTotalPage(), count);
            if (count > 0) {
                List<UserMessageVo> serveMessage = baseMapper.getServeMessage(userId, userMessageDto.getMessageType(),
                        userMessageDto.getPageSize(), userMessageDto.getTotalPage());
                for (UserMessageVo userMessageVo : serveMessage) {
                    userMessageVo.setMessageCount(merchantUserChatMap.get(userMessageVo.getMerchantId()).size());
                    userMessageVo.setMerchantImg(minioStr + userMessageVo.getMerchantImg());
                    userMessageVo.setFile(minioStr + userMessageVo.getFile());
                }
                servePage.setRecords(serveMessage);
            }
            return servePage;
        } else {
            //交易物流、售后保障、客服消息、互动消息、系统消息
            Long userMessageCount = baseMapper.getUserMessageCount(userId, userMessageDto.getMessageType());
            Page<UserMessageVo> page = new Page<>(userMessageDto.getPageSize(), userMessageDto.getTotalPage(), userMessageCount);
            if (userMessageCount > 0) {
                List<UserMessageVo> userMessage = baseMapper.getUserMessage(userId, userMessageDto.getMessageType(),
                        userMessageDto.getPageSize(), userMessageDto.getTotalPage());
                for (UserMessageVo userMessageVo : userMessage) {
                    userMessageVo.setMerchantImg(minioStr + userMessageVo.getMerchantImg());
                    userMessageVo.setFile(minioStr + userMessageVo.getFile());
                }
                page.setRecords(userMessage);
            }
            return page;
        }
    }

}
